package pzl.com.canvasapi.views;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import pzl.com.canvasapi.R;

/**
 * @author zl.peng
 * @version [1.0, 2016-11-18]
 */
public class V_SaveLayer3 extends View {
    Bitmap b;
    Drawable d;
    int w = 150;
    int h = 150;
    int curx;
    int cury;

    Paint mPaint = new Paint();
    TextPaint tp = new TextPaint();
    private static final int LAYER_FLAGS = Canvas.MATRIX_SAVE_FLAG | Canvas.CLIP_SAVE_FLAG
            | Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.FULL_COLOR_LAYER_SAVE_FLAG
            | Canvas.CLIP_TO_LAYER_SAVE_FLAG;


    public V_SaveLayer3(Context context) {
        super(context);
    }

    public V_SaveLayer3(Context context, AttributeSet attrs) {
        super(context, attrs);
        b = BitmapFactory.decodeResource(context.getResources(), R.drawable.test1);
        d = new BitmapDrawable(b);
    }

    public V_SaveLayer3(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        curx = getWidth() / 2 - w / 2;
        cury = getHeight() / 2 - h / 2;
        setBounds();
    }

    private void setBounds() {
        d.setBounds(curx, cury, curx + w, cury + h);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawBg(canvas);
        drawMove(canvas);
        drawOver(canvas);
    }

    private void drawBg(Canvas c) {
        c.saveLayer(0 + 20, 0 + 20, getWidth() - 40, getHeight() - 40, mPaint);
        c.drawColor(Color.GRAY);
        c.restore();
    }

    private void drawMove(Canvas c) {
        c.saveLayer(0, 0, getWidth(), getHeight(), mPaint);
        d.draw(c);
        c.restore();
    }

    private void drawOver(Canvas c) {
        c.saveLayerAlpha(0, 0, getWidth(), getHeight(), 60, LAYER_FLAGS);
        mPaint.setColor(Color.BLUE);
        tp.setTextSize(22);
        tp.setStrokeWidth(8);
        c.drawCircle(getWidth() / 2, getHeight() / 2, 200, mPaint);
        c.restore();
        c.drawText("over layer", getWidth() / 2 - 100, getHeight() / 2 - 100, tp);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        getParent().requestDisallowInterceptTouchEvent(true);
        curx = (int) event.getX();
        cury = (int) event.getY();
        setBounds();
        invalidate();
        return true;
    }
}
